#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr
};

// TODO
const int backlog = 10;

// 封装网络套接字
class Sock
{
public:
    Sock()
    {
    }

    ~Sock()
    {
    }

public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0); // 创建Ipv4，tcp套接字
        if (sockfd_ < 0)                           // 套接字创建失败
        {
            lg(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(SocketErr);
        }
        int opt=1;
        setsockopt(sockfd_,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));
    }

    void Bind(uint16_t port) // 绑定套接字
    {
        struct sockaddr_in local;         // 创建需要绑定的套接字
        memset(&local, 0, sizeof(local)); // 初始化填充套接字
        local.sin_family = AF_INET;       // 设置套接字为Ipv4
        local.sin_port = htons(port);     // 设置端口，同时将端口的主机序列转换为网络序列
        local.sin_addr.s_addr = INADDR_ANY;

        // 绑定套接字
        if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error,%s: %d", strerror(errno), errno);
            exit(BindErr);
        }
    }

    void Listen() // 监听方式
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen errno, %s: %d", strerror(errno), errno);
            exit(ListenErr);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport) // 获取连接的接口
    {
        struct sockaddr_in peer; // 创建连接的套接字
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len); // 获取新的连接套接字
        if (newfd < 0)                                               // 获取连接失败
        {
            lg(Warning, "accept error, %s: %d", strerror(errno), errno);
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr)); // 转换ip
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port); // 网络序列转换为主机序列

        return newfd;
    }

    bool Connect(const std::string &ip, const uint16_t &port) // 进行套接字的连接
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n = connect(sockfd_, (struct sockaddr *)&peer, sizeof(peer));
        if (n == -1)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }

    void Close()
    {
        close(sockfd_);
    }

    int Fd()
    {
        return sockfd_;
    }

private:
    int sockfd_; // 套接字fd
};